﻿using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;


namespace StagingAreaETL
{
    /// <summary>
    /// This dimension is not supposed to be changed anyhow. It should be stored just
    /// to be able to get its TermKEY for reference
    /// </summary>
    internal class TermDIM
    {
        internal TermDIM(int termKey, DateTime start, DateTime end)
        {
            NaturalKEY = termKey;
            Start = start;
            End = end;
        }
        

        internal readonly int NaturalKEY;
        internal readonly DateTime Start;
        internal readonly DateTime End;


        /// <summary>
        /// Returns TRUE if given time falls inside this term.
        /// </summary>
        internal bool IsInside(DateTime time)
        {
            return time >= Start && time <= End;
        }
    }



    internal class TermManagement
    {
        private readonly List<TermDIM> terms = new List<TermDIM>();



        internal void DownloadTerms()
        {
            MySqlConnection connection = DBHelper.getSAConnection();
            MySqlCommand command = connection.CreateCommand();

            command.CommandText = "select TermKey, StartDate, EndDate from Term";
            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                int termKey = reader.GetInt32("TermKey");
                DateTime start = reader.GetDateTime("StartDate");
                DateTime end = reader.GetDateTime("EndDate");

                terms.Add(new TermDIM(termKey, start, end));
            }

            connection.Close();
        }


        internal TermDIM getTerm(DateTime time)
        {
            foreach (TermDIM term in terms)
            {
                if (term.IsInside(time))
                    return term;
            }

            throw new ArgumentOutOfRangeException("Given time is out of handled terms interval");
        }

    }
}
